package cn.com.shadowless.xinning.view.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mengpeng.mphelper.ToastUtils;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.adapter.CommunicateAdapter;
import cn.com.shadowless.xinning.adapter.TravelAdapter;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.order.CommunicateOrderInfo;
import cn.com.shadowless.xinning.presenter.OrderPresenter;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.view.BaseFragment;
import cn.com.shadowless.xinning.view.activity.OfficeActivity;

/**
 * The type Communicate fragment.
 *
 * @author sHadowLess
 */
public class CommunicateFragment extends BaseFragment {

    /**
     * The Communicate receipt info receipt num.
     */
    @BindView(R.id.communicate_receiptInfo_ReceiptNum)
    TextView communicateReceiptInfoReceiptNum;
    /**
     * The Communicate receipt info make time.
     */
    @BindView(R.id.communicate_receiptInfo_MakeTime)
    TextView communicateReceiptInfoMakeTime;
    /**
     * The Communicate receipt info maker.
     */
    @BindView(R.id.communicate_receiptInfo_Maker)
    TextView communicateReceiptInfoMaker;
    /**
     * The Communicate receipt info making depart.
     */
    @BindView(R.id.communicate_receiptInfo_MakingDepart)
    TextView communicateReceiptInfoMakingDepart;
    /**
     * The Communicate receipt info position job.
     */
    @BindView(R.id.communicate_receiptInfo_PositionJob)
    TextView communicateReceiptInfoPositionJob;
    /**
     * The Communicate personal details proposer.
     */
    @BindView(R.id.communicate_personalDetails_Proposer)
    TextView communicatePersonalDetailsProposer;
    /**
     * The Communicate personal details proposer depart.
     */
    @BindView(R.id.communicate_personalDetails_ProposerDepart)
    TextView communicatePersonalDetailsProposerDepart;
    /**
     * The Communicate personal details position.
     */
    @BindView(R.id.communicate_personalDetails_Position)
    TextView communicatePersonalDetailsPosition;
    /**
     * The Communicate personal details date of entry.
     */
    @BindView(R.id.communicate_personalDetails_DateOfEntry)
    TextView communicatePersonalDetailsDateOfEntry;
    /**
     * The Communicate personal details expected num.
     */
    @BindView(R.id.communicate_personalDetails_ExpectedNum)
    TextView communicatePersonalDetailsExpectedNum;
    /**
     * The Communicate personal details custom name.
     */
    @BindView(R.id.communicate_personalDetails_CustomName)
    TextView communicatePersonalDetailsCustomName;
    /**
     * The Communicate personal details currency.
     */
    @BindView(R.id.communicate_personalDetails_Currency)
    TextView communicatePersonalDetailsCurrency;

    /**
     * The Communicate personal details goody bag.
     */
    @BindView(R.id.communicate_personalDetails_GoodyBag)
    TextView communicatePersonalDetailsGoodyBag;
    /**
     * The Communicate work plan.
     */
    @BindView(R.id.communicate_workPlan)
    LinearLayout communicateWorkPlan;
    /**
     * The Communicate communication cost apply amount.
     */
    @BindView(R.id.communicate_communicationCost_ApplyAmount)
    TextView communicateCommunicationCostApplyAmount;
    /**
     * The Communicate communication cost reimbursement amount.
     */
    @BindView(R.id.communicate_communicationCost_ReimbursementAmount)
    TextView communicateCommunicationCostReimbursementAmount;
    /**
     * The Communicate communication cost differences amount.
     */
    @BindView(R.id.communicate_communicationCost_DifferencesAmount)
    TextView communicateCommunicationCostDifferencesAmount;
    /**
     * The Communicate depart total reimbursed expenses.
     */
    @BindView(R.id.communicate_departTotal_ReimbursedExpenses)
    TextView communicateDepartTotalReimbursedExpenses;
    /**
     * The Communicate depart total reimbursement expenses.
     */
    @BindView(R.id.communicate_departTotal_ReimbursementExpenses)
    TextView communicateDepartTotalReimbursementExpenses;
    /**
     * The Communicate budget info social expenses.
     */
    @BindView(R.id.communicate_budgetInfo_SocialExpenses)
    TextView communicateBudgetInfoSocialExpenses;
    /**
     * The Communicate attach info.
     */
    @BindView(R.id.communicate_attachInfo)
    RecyclerView communicateAttachInfo;
    /**
     * The Communicate check process.
     */
    @BindView(R.id.communicate_check_Process)
    LinearLayout communicateCheckProcess;
    /**
     * The Communicate communicate check process.
     */
    @BindView(R.id.communicate_communicateCheck_Process)
    LinearLayout communicateCommunicateCheckProcess;

    private final String forMat = "%s，预算总金额：%s\n已报销：%s\n报销中：%s\n剩余可报销：%s\n已申请未报销：%s\n在申请未报销：%s\n剩余可申请：%s";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_communication_layout;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        if (null != bundle) {
            String orderId = bundle.getString("orderId");
            String userName = bundle.getString("userName");
            initCommunicateInfo(orderId, userName);
        }
    }

    @Override
    protected void initView() {

    }

    private void initCommunicateInfo(String orderId, String userName) {
        OrderPresenter
                .getSingleton()
                .getCommunicateInfo(orderId, userName, new RequestCallBack<CommunicateOrderInfo>() {
                    @Override
                    public void success(RequestResult<CommunicateOrderInfo> result) {
                        String token = result.getLoginToken();
                        String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                        if (result.isSucceed() && null != result.getResult()) {
                            if (null != token && token.equals(oldToken)) {
                                Log.e(TAG, "success: " + result.toString());
                                CommunicateOrderInfo.DataBean dataBean = result.getResult().getData();
                                CommunicateOrderInfo.DataBean.BudgetItemObjectBean budgetItemObjectBean = dataBean.getBudgetItemObject();
                                CommunicateOrderInfo.DataBean.CreateUserObjectBean createUserObjectBean = dataBean.getCreateUserObject();
                                List<CommunicateOrderInfo.DataBean.ItemListBean> itemListBean = dataBean.getItemList();
                                List<CommunicateOrderInfo.DataBean.HistoryListBean> historyListBean = dataBean.getHistoryList();
                                List<CommunicateOrderInfo.DataBean.FileListDTO> fileList = dataBean.getFileList();

                                String id = dataBean.getId();
                                String createTimeStr = dataBean.getCreateTimeStr();
                                String userName = createUserObjectBean.getUserName();
                                String departmentName = dataBean.getDepartmentName();
                                String positionName = createUserObjectBean.getPositionName();
                                communicateReceiptInfoReceiptNum.setText(id);
                                communicateReceiptInfoMakeTime.setText(createTimeStr);
                                communicateReceiptInfoMaker.setText(userName);
                                communicateReceiptInfoMakingDepart.setText(departmentName);
                                communicateReceiptInfoPositionJob.setText(positionName);

                                String inDateStr = dataBean.getInDateStr();
                                String peopleCount = dataBean.getPeopleCount() + "";
                                String customerName = dataBean.getCustomerName();
                                boolean isTemp = dataBean.isTemp();
                                communicatePersonalDetailsProposer.setText(userName);
                                communicatePersonalDetailsProposerDepart.setText(departmentName);
                                communicatePersonalDetailsPosition.setText(positionName);
                                communicatePersonalDetailsCurrency.setText("人民币");
                                communicatePersonalDetailsDateOfEntry.setText(inDateStr);
                                communicatePersonalDetailsExpectedNum.setText(peopleCount);
                                communicatePersonalDetailsCustomName.setText(customerName);
                                if (isTemp) {
                                    communicatePersonalDetailsGoodyBag.setText("√ 是否暂支");
                                } else {
                                    communicatePersonalDetailsGoodyBag.setText("X 是否暂支");
                                }
                                for (CommunicateOrderInfo.DataBean.ItemListBean data : itemListBean) {
                                    View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_communicate_tab_item, null, false);
                                    LinearLayout tabItem = view.findViewById(R.id.communicate_tab_Item);
                                    TextView dateOfCommunicate = view.findViewById(R.id.communicate_tab_DateOfCommunicate);
                                    TextView communicateType = view.findViewById(R.id.communicate_tab_CommunicateType);
                                    TextView communicateStyle = view.findViewById(R.id.communicate_tab_CommunicateStyle);
                                    TextView communicateTabTaxiCode = view.findViewById(R.id.communicate_tab_taxiCode);
                                    TextView communicateTabReimbursementWithoutAmount = view.findViewById(R.id.communicate_tab_ReimbursementWithoutAmount);
                                    TextView communicateInstructions = view.findViewById(R.id.communicate_tab_CommunicateInstructions);
                                    TextView local = view.findViewById(R.id.communicate_tab_Local);
                                    TextView customName = view.findViewById(R.id.communicate_tab_CustomName);
                                    TextView customDuty = view.findViewById(R.id.communicate_tab_CustomDuty);
                                    TextView customLevel = view.findViewById(R.id.communicate_tab_CustomLevel);
                                    TextView dutyWithCompany = view.findViewById(R.id.communicate_tab_DutyWithCompany);
                                    TextView companyPeople = view.findViewById(R.id.communicate_tab_CompanyPeople);
                                    TextView amount = view.findViewById(R.id.communicate_tab_Amount);
                                    TextView reimbursableAmount = view.findViewById(R.id.communicate_tab_ReimbursableAmount);
                                    TextView attachment = view.findViewById(R.id.communicate_tab_Attachment);
                                    TextView abstractTxt = view.findViewById(R.id.communicate_tab_Abstract);

                                    String payCostNoDuty = getDecimal(data.getPayCostNoDuty().doubleValue());
                                    String taxiCode = data.getTaxCode();
                                    String communicationDateStr = data.getCommunicationDateStr();
                                    String typeName = data.getTypeName();
                                    String wayName = data.getWayName();
                                    String communicationContent = data.getCommunicationContent();
                                    String address = data.getAddress();
                                    String name = data.getName();
                                    String duty = data.getDuty();
                                    String customerLevelStr = data.getCustomerLevelStr();
                                    String dutyRange = data.getDutyRange();
                                    String attendPeople = data.getAttendPeople();
                                    String cost = getDecimal(data.getCost().doubleValue());
                                    String payCost = getDecimal(data.getPayCost().doubleValue());
                                    String fileCount = data.getFileCount() + "";
                                    String remark = data.getRemark();
                                    communicateTabReimbursementWithoutAmount.setText(payCostNoDuty);
                                    communicateTabTaxiCode.setText(taxiCode);
                                    dateOfCommunicate.setText(communicationDateStr);
                                    communicateType.setText(typeName);
                                    communicateStyle.setText(wayName);
                                    communicateInstructions.setText(communicationContent);
                                    local.setText(address);
                                    customName.setText(name);
                                    customDuty.setText(duty);
                                    customLevel.setText(customerLevelStr);
                                    dutyWithCompany.setText(dutyRange);
                                    companyPeople.setText(attendPeople);
                                    amount.setText(cost);
                                    reimbursableAmount.setText(payCost);
                                    attachment.setText(fileCount);
                                    abstractTxt.setText(remark);
                                    communicateWorkPlan.addView(tabItem);
                                }

                                BigDecimal totalCost = dataBean.getTotalCost();
                                BigDecimal totalPayCost = dataBean.getTotalPayCost();
                                communicateCommunicationCostApplyAmount.setText(getDecimal(totalCost.doubleValue()));
                                communicateCommunicationCostReimbursementAmount.setText(getDecimal(totalPayCost.doubleValue()));
                                communicateCommunicationCostDifferencesAmount.setText(getDecimal(totalCost.doubleValue() - totalPayCost.doubleValue()));

                                String reimbursedMoney = getDecimal(budgetItemObjectBean.getReimbursedMoney().doubleValue());
                                String reimbursingMoney = getDecimal(budgetItemObjectBean.getReimbursingMoney().doubleValue());
                                communicateDepartTotalReimbursedExpenses.setText(reimbursedMoney);
                                communicateDepartTotalReimbursementExpenses.setText(reimbursingMoney);

                                String budgetInfo = budgetItemObjectBean.getBudgetInfo();
                                String allMoney = getDecimal(budgetItemObjectBean.getAllMoney().doubleValue());
                                String reimbursedCrash = getDecimal(budgetItemObjectBean.getReimbursedMoney().doubleValue());
                                String reimbursingCrash = getDecimal(budgetItemObjectBean.getReimbursingMoney().doubleValue());
                                String remainReimburseMoney = getDecimal(budgetItemObjectBean.getRemainReimburseMoney().doubleValue());
                                String applyedMoney = getDecimal(budgetItemObjectBean.getApplyedMoney().doubleValue());
                                String applyingMoney = getDecimal(budgetItemObjectBean.getApplyingMoney().doubleValue());
                                String remainApplyMoney = getDecimal(budgetItemObjectBean.getRemainApplyMoney().doubleValue());
                                communicateBudgetInfoSocialExpenses.setText(
                                        String.format(
                                                forMat,
                                                budgetInfo,
                                                allMoney,
                                                reimbursedCrash,
                                                reimbursingCrash,
                                                remainReimburseMoney,
                                                applyedMoney,
                                                applyingMoney,
                                                remainApplyMoney
                                        )
                                );

                                communicateAttachInfo.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
                                CommunicateAdapter communicateAdapter = new CommunicateAdapter(R.layout.fragment_communicate_item, fileList);
                                communicateAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                                    String fileName = fileList.get(position).getFileName();
                                    String fileUrl = fileList.get(position).getFileUrl();
                                    Intent intent = new Intent(mActivity, OfficeActivity.class);
                                    intent.putExtra("fileName", fileName);
                                    intent.putExtra("fileUrl", fileUrl);
                                    mActivity.startActivity(intent);
                                });
                                communicateAttachInfo.setAdapter(communicateAdapter);
                                communicateAdapter.notifyDataSetChanged();

                                for (CommunicateOrderInfo.DataBean.HistoryListBean bean : historyListBean) {
                                    String checkType = bean.getCheckType();
                                    if ("A".equals(checkType)) {
                                        View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_order_process_item, null, false);
                                        LinearLayout linearLayout = view.findViewById(R.id.general_check_Process_Item);
                                        TextView time = view.findViewById(R.id.general_check_Process_Time);
                                        TextView link = view.findViewById(R.id.general_check_Process_Link);
                                        TextView name = view.findViewById(R.id.general_check_Process_Name);
                                        TextView status = view.findViewById(R.id.general_check_Process_Status);
                                        String checkTime = bean.getCheckTimeStr();
                                        String checkAccountUserName = bean.getCheckAccountName();
                                        String processName = bean.getProcessName();
                                        String statusStr = bean.getStatusStr();
                                        time.setText(checkTime);
                                        name.setText(String.format("%s(%s)", checkAccountUserName, processName));
                                        status.setText(statusStr);
                                        if ("待审核".equals(statusStr)) {
                                            time.setTextColor(Color.parseColor("#4a80ef"));
                                            link.setTextColor(Color.parseColor("#4a80ef"));
                                            name.setTextColor(Color.parseColor("#4a80ef"));
                                            status.setTextColor(Color.parseColor("#4a80ef"));
                                        }
                                        communicateCheckProcess.addView(linearLayout);
                                    } else if ("C".equals(checkType)) {
                                        View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_order_process_item, null, false);
                                        LinearLayout linearLayout = view.findViewById(R.id.general_check_Process_Item);
                                        TextView time = view.findViewById(R.id.general_check_Process_Time);
                                        TextView link = view.findViewById(R.id.general_check_Process_Link);
                                        TextView name = view.findViewById(R.id.general_check_Process_Name);
                                        TextView status = view.findViewById(R.id.general_check_Process_Status);
                                        String checkTime = bean.getCheckTimeStr();
                                        String checkAccountUserName = bean.getCheckAccountName();
                                        String processName = bean.getProcessName();
                                        String statusStr = bean.getStatusStr();
                                        time.setText(checkTime);
                                        name.setText(String.format("%s(%s)", checkAccountUserName, processName));
                                        status.setText(statusStr);
                                        if ("待审核".equals(statusStr)) {
                                            time.setTextColor(Color.parseColor("#4a80ef"));
                                            link.setTextColor(Color.parseColor("#4a80ef"));
                                            name.setTextColor(Color.parseColor("#4a80ef"));
                                            status.setTextColor(Color.parseColor("#4a80ef"));
                                        }
                                        communicateCommunicateCheckProcess.addView(linearLayout);
                                    }
                                }
                            } else {
                                ToastUtils.onErrorShowToast("登录态与服务器不一致");
                                initLogoutInfo(mActivity, userName);
                            }
                        } else {
                            ToastUtils.onErrorShowToast("该订单暂无详细信息");
                        }
                    }

                    @Override
                    public void fail(String errorMsg) {
                        ToastUtils.onErrorShowToast(errorMsg);
                    }
                });
    }
}
